package com.vmap.longitude;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import com.vmap.longitude.Road;

import com.vmap.longitude.RoadProvider;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class LongitudeActivity extends MapActivity {
	 
 MapController mapController;
 MyPositionOverlay positionOverlay;
 private static double endlatitude;
 private static double endlongitude;
 private static double distance;
 private Location dest;
 private Road mRoad; 
 private static int flag=0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	 super.onCreate(savedInstanceState);
	 setContentView(R.layout.main);
	 Intent sender = getIntent();
	 double []geopoint={0};
	 if(sender != null && sender.getExtras() != null)
	 {
		 
		 geopoint = sender.getExtras().getDoubleArray("endlocation");
		 if(geopoint != null)
		 {
			 
		 endlatitude=geopoint[0];
		 endlongitude=geopoint[1];
		 distance=geopoint[2];
		 dest = new Location(LocationManager.GPS_PROVIDER);
		 dest.setLatitude(endlatitude);
		 dest.setLongitude(endlongitude);
		 sender = null;
		 }
	 }
 	   // Get a reference to the MapView
	 MapView myMapView = (MapView)findViewById(R.id.myMapView);
	 myMapView.setBuiltInZoomControls(true);
	 // Get the Map Views controller
	mapController = myMapView.getController();
	// Configure the map display options
	myMapView.setSatellite(false);
	myMapView.setStreetView(true);
	myMapView.displayZoomControls(true);
	// Zoom in
	mapController.setZoom(17);  
 
	// Add the MyPositionOverlay
	positionOverlay = new MyPositionOverlay();
	List<Overlay> overlays = myMapView.getOverlays();
	overlays.add(positionOverlay);

	LocationManager locationManager;
	String context = Context.LOCATION_SERVICE;
	locationManager = (LocationManager)getSystemService(context);
		
	    //Define Criteria object
	    Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		
		
	 //String provider = LocationManager.NETWORK_PROVIDER; 	
	String provider = locationManager.getBestProvider(criteria, true);
	Location location =locationManager.getLastKnownLocation(provider);
	
	//in case location is still null , use values from Network Provider
	if (location ==null)
	{ 
        
		Log.d("androLongitude","location was null , using networkprovider");
		location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	}
	updateWithNewLocation(location);
	locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);
	}
	
	
	@Override
	 protected boolean isRouteDisplayed() {
		return false; 
	}
	
    
    private final LocationListener locationListener = new LocationListener() {
    	public void onLocationChanged(Location location) {
    	updateWithNewLocation(location);
    	}
    	public void onProviderDisabled(String provider){
    	updateWithNewLocation(null);
    	}
    	public void onProviderEnabled(String provider){ }
    	public void onStatusChanged(String provider, int status,
    	Bundle extras){ }
    	};
   
   @Override
  public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.menu, menu);
   return true;
    }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle item selection
       switch (item.getItemId()) {
           case R.id.track_time:
        	   Toast.makeText(this, "Dummy toast, give a call to your activity", Toast.LENGTH_LONG).show(); 
               return true;
           case R.id.help:
        	   Toast.makeText(this, "Dummy toast, give a call to your activity", Toast.LENGTH_LONG).show();
               return true;
           case R.id.proximity:
        	   Intent i = new Intent(this, Proximity.class);
        	   i.putExtra("parentClass", LongitudeActivity.class);
        	   startActivity(i);
           default:
               return super.onOptionsItemSelected(item);
       }
   } 

    	
    public void updateWithNewLocation(Location location) { 
    	
     	String latLongString;
    		
    	String addressString = "No address found";
    	 if (location != null) {
    		  //update the overlay
    		 positionOverlay.setLocation(location);
    		 
    		// Update the map location.
    		 Double geoLat = location.getLatitude()*1E6;
    		 Double geoLng = location.getLongitude()*1E6;
    		 GeoPoint point = new GeoPoint(geoLat.intValue(),
    		 geoLng.intValue());
    		 
    		 mapController.animateTo(point);
    	    // float [] results ={0}; 
    	     
    	     if (dest != null)
    	     {
    	    	 Double endLat = endlatitude*1E6;
        		 Double endLng = endlongitude*1E6;
        		 GeoPoint point2 = new GeoPoint(endLat.intValue(),endLng.intValue());
        		 mapController.animateTo(point2);
    	    	 float remDistance=location.distanceTo(dest);
    	    	 float remRouteDistance = 0;
    	    	 
    	    	 String url = RoadProvider.getUrl(location.getLatitude(), location.getLongitude(), endlatitude, endlongitude); 
    	    	 InputStream is = getConnection(url); 
    	    	 if(is != null)
    	    	 {
    	    		 mRoad = RoadProvider.getRoute(is); 
    	    	 	Log.d("androLongitude", "" + (mRoad.mDescription.toString()));
    	    	 
    	    	 	String rd=mRoad.mDescription.toString();
    	    	 	rd = rd.substring(rd.indexOf(" ") + 1, rd.indexOf("k"));
    	    	 	remRouteDistance = Float.parseFloat(rd);
    	    	 }
    	    	 //Location.distanceBetween(location.getLatitude(), location.getLongitude(), endlatitude, endlongitude, results );	
    	    	 Log.d("androLongitude","remaining distance " + remDistance + "remaining Route Distance" + remRouteDistance); 
    	    	 if (remRouteDistance == 0)
    	    	 {
    	    		 remRouteDistance=remDistance/1000;
    	    	 }
    	    	 
    	    	 if(distance > 0 && remRouteDistance <= distance/1000)
    	    	 {
    	    		 String number = "9971110423";
    	    		 
    	    		 Toast.makeText(this, "you are in proximity range", Toast.LENGTH_LONG).show(); 
    	             //startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
    	    		 if (flag == 0)
    	    		 {	 
    	    			 sendSMS(number, "I have reached");
    	    			 flag =1;
    	    		 }
    	    	 }
    	    	 else
    	    	 {
    	    		 Toast.makeText(this, "you are " + remRouteDistance + " kilometres from destination", Toast.LENGTH_LONG).show();
    	    		 flag =0;
    	    	 }
    	     }
    	      Log.d("androLongitude","location.getLatitude returned " + geoLat); 
    	      Log.d("androLongitude","location.getLongitude returned " + geoLng); 
      
    	 }
    	}    
     


private InputStream getConnection(String url) { 
    InputStream is = null; 
    try { 
            URLConnection conn = new URL(url).openConnection(); 
            is = conn.getInputStream(); 
    } catch (MalformedURLException e) { 
            e.printStackTrace(); 
    } catch (IOException e) { 
            e.printStackTrace(); 
    } 
    return is; 
} 


private void sendSMS(String phoneNumber, String message)
{        
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, LongitudeActivity.class), 0);                
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, pi, null);        
}
}